import { setGlobal } from '@swda/utils'
//import { blackList } from '@swda/Scene/SynthesisMenu/formulaSheet.js'
import { isInBlackList } from "@swda/Scene/SynthesisMenu/synthesisLogic";
//--------------------------------------------------------------------------
// Window_EnemyInfo
// 敌人数据

function Window_EnemyInfo() {
    this.initialize.apply(this, arguments);
}

Window_EnemyInfo.prototype = Object.create(Window_Selectable.prototype);
Window_EnemyInfo.prototype.constructor = Window_EnemyInfo;

Window_EnemyInfo.prototype.update = function() {
    Window_Selectable.prototype.update.call(this);
    this.updatePreview();
};

Window_EnemyInfo.prototype.initialize = function() {
    const [x,y,w,h] = [440,100,800,584];
    Window_Selectable.prototype.initialize.call(this, x,y,w,h);
    this._requestEnemyPreviewRefresh = false;
    this._enemy = null;
    this._longSkillList = 0; //超出数量
    this._enemyPreview = new Sprite();
    
    this.addChild(this._enemyPreview);
    
    this.refresh();
};

Window_EnemyInfo.prototype.setEnemy = function(enemy) {
    if (this._enemy !== enemy) {
        this._enemy = enemy;
        this.refresh();
    }
};

Window_EnemyInfo.prototype.refresh = function() {
    this.contents.clear();

    if (this._enemy) {
        if($gameSystem.isInEnemyBook(this._enemy)){
            const [px, py, opacity] = [58, 52, 0];
            this._enemyPreview.x = px;
            this._enemyPreview.y = py;
            this._enemyPreview.opacity = opacity;
            var y = 8;
            //const lineHeight = this.lineHeight();
            this.drawPreview();      // 战斗图
            this.drawBlock1( y );    // 名称等级
            y += this.titleFontSize() + this.smallerLineHeight() * 0.5;
            this.drawBlockSkill( y );// 奇术
            this.drawBlock2( y );    // 核心数值+其它数值
            y += this.smallerLineHeight()
            this.drawBlock3( y) ;    // 额外信息（攻击附加、状态免疫、属性抗性）
            y += this.smallerLineHeight() * 5
            this.drawBlockReward( y );    // 奖励
            y += this.smallerLineHeight() * 4;
            this.drawBlockExtra( y );    // 额外信息：物理抗性、仙术抗性等
            this.drawBlockPet( y );    // 额外信息：收化、召唤、装备、炼化材料、炼化产物
            y += this.smallerLineHeight() * 3;
            this.drawBlock6( y );    // 说明文
        }else{
            this._enemyPreview.bitmap = '';
        }
    }
};

Window_EnemyInfo.prototype.blockWidth = function(y) {
    return 148;
};
Window_EnemyInfo.prototype.imageWidth = function(y) {
    return 248;
};

Window_EnemyInfo.prototype.enemy = function() {
    const enemy = new Game_Enemy(this._enemy.id, 0, 0);
    return enemy
};

Window_EnemyInfo.prototype.isIdentified = function() {
    return $gameSystem.identifyRate(this._enemy.id) >= 100;
};
// 基本信息（名称、击杀数）
Window_EnemyInfo.prototype.drawBlock1 = function(y) {
    var dx = this.imageWidth() + 12;
    // 绘制名称
    this.setTitleFont();
    this.drawText(this._enemy.name.split('（')[0], dx, y);
    // 绘制击杀数    
    dx += 2 * this.blockWidth();
    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText("击杀数", dx, y);
    this.resetTextColor();
    this.drawText($gameSystem.defeatNumber(this._enemy.id), dx + 66 + 8, y);
    this.resetFontSettings();
};
// 技能列表
Window_EnemyInfo.prototype.drawBlockSkill = function(y) {
    const lineHeight = this.smallerLineHeight();
    const dx = this.imageWidth() + this.blockWidth()*2 + 12;

    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.skill, dx, y);
    this.resetTextColor();
    y += lineHeight;
    
    let skillCount = 0;

    for (var i = 0; i < this._enemy.actions.length; i++) {
        if (this._enemy.actions[i].skillId>6){
            var skill = $dataSkills[this._enemy.actions[i].skillId];
            if (!DataManager.isAttack(skill)){
                if (this.isIdentified()){
                    this.drawItemName(skill, dx, y );
                } else {
                    this.drawText("？？？？？", dx, y );
                }
                skillCount++;
                y += lineHeight;
            }
        }
        
    }

    if (skillCount <= 0){
		this.drawText('无', dx, y);
	}

    if(skillCount>5){
        this._longSkillList = skillCount-5;
    }else{
        this._longSkillList = 0;
    }
};

// 核心数值（命仙体）及其它数值
Window_EnemyInfo.prototype.drawBlock2 = function(y) {
    const lineHeight = this.smallerLineHeight();
    const dx = this.imageWidth() + 12;

    // 绘制等级
    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.level, dx, y);
    this.resetTextColor();
    this.drawText(this.enemy().catchLevel(), dx + 66, y);
    y += lineHeight;
     /////////////////////////////////////

    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.hp, dx, y);
    this.resetTextColor();
    this.drawText(this.enemy().hp, dx + 66, y);
    y += lineHeight;

    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.mp, dx, y);
    this.resetTextColor();
    if (this.isIdentified())
        this.drawText(this.enemy().mp, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    y += lineHeight;

    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.tp, dx, y);
    this.resetTextColor();
    
    if (this.isIdentified())
        this.drawText(this.enemy().tp, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    y += lineHeight;


    /////////////////////////////////////
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(2), dx, y);
    this.resetTextColor();
    if (this.isIdentified())
        this.drawText(this.enemy().atk, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    y += lineHeight;

    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(3), dx, y);
    this.resetTextColor();
    if (this.isIdentified())
        this.drawText(this.enemy().def, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    y += lineHeight;


    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(4), dx, y);
    this.resetTextColor();
    if (this.isIdentified())
        this.drawText(this.enemy().mat, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    y += lineHeight;

    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(5), dx, y);
    this.resetTextColor();
    if (this.isIdentified())
        this.drawText(this.enemy().mdf, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    y += lineHeight;


    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(6), dx, y);
    this.resetTextColor();
    if (this.isIdentified())
        this.drawText(this.enemy().agi, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    //y += lineHeight;

   /* 
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(7), dx, y);
    this.resetTextColor();
    if (this.isIdentified())
        this.drawText(this.enemy().luk, dx + 66, y);
    else
        this.drawText("？", dx + 66, y);
    */
    this.resetFontSettings();
};

// 显示额外信息（攻击附加状态、状态免疫、属性抗性）
Window_EnemyInfo.prototype.drawBlock3 = function(y) {
    const lineHeight = this.smallerLineHeight();
    const dx = this.imageWidth() + this.blockWidth() + 8;

    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText("攻击附加", dx, y);
    this.resetTextColor();
    y += lineHeight 
    if (this.isIdentified()){
        this.drawStates(this.enemy().attackStates(), dx, y);
    } else {
        this.drawText("？？？？？", dx, y );
    }
    

    y += lineHeight 
    this.changeTextColor(this.systemColor());
    this.drawText("状态免疫", dx, y);
    this.resetTextColor();
    y += lineHeight
    if (this.isIdentified()){
        let statesResist = this.enemy().stateResistSet();
        statesResist = statesResist.filter((item, index) => statesResist.indexOf(item) === index);
        this.drawStates(statesResist, dx, y);
    } else {
        this.drawText("？？？？？", dx, y );
    }
    this.resetTextColor();
    this.resetFontSettings();
    y += lineHeight;
    y += lineHeight;
    const infoArray = [1, 2, 3];
    for (var i = 0; i < infoArray.length; ++i) {
        this.drawElementData(infoArray[i], dx, y, this.blockWidth());
        y += lineHeight;
    }
    this.resetFontSettings();
};

// 奖励（经验、钱币、物品）
Window_EnemyInfo.prototype.drawBlockReward = function(y) {
    const lineHeight = this.smallerLineHeight();
    const dx = this.imageWidth() + this.blockWidth()*2 + 12;
    y += lineHeight * this._longSkillList;
    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.exp, dx, y);
    this.resetTextColor();
    this.drawText(this._enemy.exp, dx + 66, y);
    y += lineHeight;

    this.changeTextColor(this.systemColor());
    this.drawText("钱币", dx, y);
    this.resetTextColor();
	this.drawText(this._enemy.gold, dx + 66, y);
    y += lineHeight;

    this.changeTextColor(this.systemColor());
    this.drawText("物品", dx, y);
    this.resetTextColor();
    let dropItemCount = 0;
    for (var i = 0; i < this._enemy.dropItems.length; i++)
    {
        if (this._enemy.dropItems[i].dataId === 0 || this._enemy.dropItems[i].kind === 0) continue;
        var item;
        switch (this._enemy.dropItems[i].kind) {
            case 1:
                item = $dataItems[this._enemy.dropItems[i].dataId];
                break;
            case 2:
                item = $dataWeapons[this._enemy.dropItems[i].dataId];
                break;
            case 3:
                item = $dataArmors[this._enemy.dropItems[i].dataId];
                break;
        }
        dropItemCount++;
        this.drawItemName(item, dx, y + (i + 1)*lineHeight);
    }

    if (dropItemCount <= 0){
		this.drawText('无', dx, y + 1 * lineHeight);
	}

  

    this.resetFontSettings();
}

// 额外信息：物理抗性、仙术抗性等
Window_EnemyInfo.prototype.drawBlockExtra = function(y) {
    const lineHeight = this.smallerLineHeight();
    
    let dx = 12 + 24 ;

    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText("物理抗性", dx, y);
    this.resetTextColor();
    let sparam = 0;
    if (this.isIdentified()){
        sparam = Math.round((1-this.enemy().sparam(6)) *100);
        if(sparam !== 0){
            this.changeTextColor('#59ba8e');
            this.drawText('抗' + sparam +'%', dx, y, this.imageWidth() - 60, 'right');
        }else{
            this.changeTextColor('#fbdb45');
            this.drawText('—', dx, y, this.imageWidth() - 60, 'right');
        }
    } else {
        this.drawText("？", dx, y, this.imageWidth() - 60, 'right');
    }
    y += lineHeight 
    this.changeTextColor(this.systemColor());
    this.drawText("仙术抗性", dx, y);
    this.resetTextColor();

    if (this.isIdentified()){
        sparam = Math.round((1-this.enemy().sparam(7)) *100);
        if(sparam !== 0){
            this.changeTextColor('#59ba8e');
            this.drawText('抗' + sparam +'%', dx, y, this.imageWidth() - 60, 'right');
        }else{
            this.changeTextColor('#fbdb45');
            this.drawText('—', dx, y, this.imageWidth() - 60, 'right');
        }
    } else {
        this.drawText("？", dx, y, this.imageWidth() - 60, 'right');
    }
    y += lineHeight 
 
    
    this.resetFontSettings();
}

// 额外信息：收化、召唤、装备、炼化材料、炼化产物
Window_EnemyInfo.prototype.drawBlockPet = function(y) {
    const lineHeight = this.smallerLineHeight();
    
    const d = 66;
    const d2 = this.blockWidth() - 4;
    let dx = 12 + this.imageWidth();

    this.setSmallerFont();

    //收化
    const canBeCaught = this.enemy()._canBeCaught ? "\\i[213]": "\\i[214]";
    this.changeTextColor(this.systemColor());
    this.drawText("收化", dx, y);
    this.resetTextColor();
    this.drawTextEx(canBeCaught, dx + d, y);

    //炼化
    dx += d2;
    const canSynth = !this.isEnemyInSynthBlackList() ? "\\i[213]": "\\i[214]";
    this.changeTextColor(this.systemColor());
    this.drawText("炼化", dx, y);
    this.resetTextColor();
    this.drawTextEx(canSynth, dx + d, y);

    //召唤
    dx = 12 + this.imageWidth();
    y += lineHeight;
    const canUse = CP.UseEquipManager.isEquipUsable(this.enemy().catchGainItem(16)) ? "\\i[213]": "\\i[214]";
    this.changeTextColor(this.systemColor());
    this.drawText("召唤", dx, y);
    this.resetTextColor();
    this.drawTextEx(canUse, dx + d, y);

    //装备
    dx += d2;
    $dataSystem.armorTypes[4]
    const atype = this.enemy().catchGainItem(16).atypeId;
    this.changeTextColor(this.systemColor());
    this.drawText("装备", dx, y);
    this.resetTextColor();
    if(atype == 0)
        this.drawTextEx("\\i[214]", dx + d, y);  
    else
        this.drawText($dataSystem.armorTypes[atype], dx + d + 6, y);  

  

    this.resetFontSettings();
}

// 炼妖黑名单判断
Window_EnemyInfo.prototype.isEnemyInSynthBlackList = function() {
    const item = this.enemy().catchGainItem(16)
    return isInBlackList(2, item) || isInBlackList('', this._enemy)
}

// 说明
Window_EnemyInfo.prototype.drawBlock6 = function(y) {
    const lineHeight = this.smallerLineHeight();
    var dx = 12;
    const width = this.smallerFontSize() * 34;
    this.setSmallerFont();
    //this.resetTextColor();
    if(!!this._enemy.catchGainItem){
        let text = $dataArmors[this._enemy.catchGainItem[16].itemId].description;
        //text = this.convertEscapeCharacters(text);
        this.drawTextEx(text, dx, y, width);
    }
    this.resetFontSettings();
}


Window_EnemyInfo.prototype.drawStates = function(states, x, y){
    const length = states.length;
    const d = 24;
    let total = 0;
    for(let i = 0; i < length; i++){
        let stateiconId = $dataStates[states[i]].iconIndex;
        if(stateiconId > 0){
            this.drawTextEx('\\i['+ stateiconId +']', x-6, y);
            x += d;
            total++;
        }
    }
    if(total==0)
        this.drawText('无', x, y);
}

// 修改内容：禁止改字体字号、变为根据宽度自动换行
Window_EnemyInfo.prototype.drawTextEx = function(text, x, y, width) {
    if (text) {
      //this.resetFontSettings();
      var textState = { index: 0, x: x, y: y, left: x };
      textState.text = this.convertEscapeCharacters(text);
      textState.height = this.calcTextHeight(textState, false);
      while (textState.index < textState.text.length) {
        this.processCharacter(textState, width);
      }
      return textState.x - x;
    } else {
      return 0;
    }
  };

// 修改内容：变为根据宽度自动换行、禁止\n换行
Window_EnemyInfo.prototype.processCharacter = function(textState, width) {
    if (textState.x + this.contents.fontSize > width){
        //this.processNewLine(textState);
        textState.x = textState.left;
        textState.y += textState.height;
        textState.height = this.calcTextHeight(textState, false);
        //textState.index++;
    }else{
        switch (textState.text[textState.index]) {
        case '\r':
            textState.index++;
            break;
        case '\n':
            //textState.x -= this.textWidth("\\")/2;//修正换行处错位问题
            textState.index++;
            //this.processNewLine(textState);
            break;
        case '\f':
            this.processNewPage(textState);
            break;
        case '\x1b':
            this.processEscapeCharacter(this.obtainEscapeCode(textState), textState);
            break;
        default:
            this.processNormalCharacter(textState);
            break;
        }
    }
};
  


Window_EnemyInfo.prototype.drawElementInfo = function (x, y, width) {
    var dx = x || 0;
    var dy = y || 0;
    var dw = width || 150;
    const infoArray = [1, 2, 3];
    for (var i = 0; i < infoArray.length; ++i) {
        this.drawElementName( dx, dy)
        this.drawElementData(infoArray[i], dx + 48, dy)
        dy += this.lineHeight();
    }
};

Window_EnemyInfo.prototype.drawElementData = function (eleId, dx, dy, dw) {
    var eleName = $dataSystem.elements[eleId];
    var eleRate = (this.enemy().elementRate(eleId));

    this.setSmallerFont();
    this.changeTextColor(this.systemColor());
    this.drawText(eleName, dx, dy);
    this.resetTextColor();
    if (this.isIdentified()){
        var eleText = '';
        if (eleRate > 1) {
            eleText = '损 ';
            eleRate -= 1;
            this.changeTextColor('#ff4d00');
    
        } else if (eleRate == 1) {
            eleText = '—';
            this.changeTextColor('#fbdb45');
    
        } else if (eleRate >= 0) {
            eleText = '抗 ';
            eleRate -= 1;
            this.changeTextColor('#59ba8e');
        } else {
            eleText = '吸 ';
            this.changeTextColor('#65cbff');
        }
        /*
        if (eleRate == 1) {
            var text = eleText;
        } else {
            var text = eleText + Math.abs(Math.round(eleRate * 100)).toFixed(Yanfly.Param.StatusEleDec) + '%';
        }*/
        var text = eleText;
        this.drawText(text, dx + 74, dy, dw);
    }else{
        this.drawText("？", dx + 74, dy, dw);
    }
        

    this.resetFontSettings();

};
Window_EnemyInfo.prototype.setSourceImgSize = function(sw, sh){
    this._sw = sw;
    this._sh = sh;
}
Window_EnemyInfo.prototype.drawPreview = function() {
    let lastBitmap = this._enemyPreview.bitmap;
    let newBitmap = null;
    
    switch(this._enemy.id){
        case 258:
            newBitmap = ImageManager.loadSvEnemy('245', this._enemy.battlerHue);
            break;
        case 259:
            newBitmap = ImageManager.loadSvEnemy('245_1', this._enemy.battlerHue);
            break;
        case 260:
            newBitmap = ImageManager.loadSvEnemy('245_2', this._enemy.battlerHue);
            break;
        case 261:
            newBitmap = ImageManager.loadSvEnemy('245_3', this._enemy.battlerHue);
            break;
        case 272:
            newBitmap = ImageManager.loadSvEnemy('252', this._enemy.battlerHue);
            break;
        case 273:
            newBitmap = ImageManager.loadSvEnemy('253', this._enemy.battlerHue);
            break;
        default:
            newBitmap = ImageManager.loadSvEnemy(this._enemy.battlerName, this._enemy.battlerHue);
            break;
    }

    if (newBitmap !== lastBitmap){
        this._enemyPreview.bitmap = newBitmap;
        this._enemyPreview.opacity = 0;
    }
    this._requestEnemyPreviewRefresh = true;
};

Window_EnemyInfo.prototype.updatePreview = function() {
    if (this._requestEnemyPreviewRefresh){
        if (this._enemyPreview.bitmap){
            if (this._enemyPreview.bitmap.isReady()){
                  // 原图尺寸[sw, sh]
                  let sw = this._enemyPreview.bitmap.width;
                  let sh = this._enemyPreview.bitmap.height;
                  let scale = 0.8;
                  // 目标尺寸：[192, 288]
                  const [dw,dh] = [192, 288];
                  let px = 0;
                  let py = 0;
                  let pw = sw;
                  // 0.8 * 图片高度> 目标高度：将图片按高度缩放为原图的0.8
                  if (sh > dh){
                      scale = scale * dh/sh;
                  }
                  // 特殊情况尺寸修正
                  if([18,252,253,274,275,284].contains(this._enemy.id)){
                    scale *= 1.22;
                  }
                  if(this._enemy.id == 285){
                    scale *= 1.8;
                  }
                  if([28,71,93,267].contains(this._enemy.id)){
                    scale *= 0.75;
                  }
                  if([276, 277, 278].contains(this._enemy.id)){
                    scale *= 0.6;
                  }
                  

                  // 如果上一步缩放后图片宽度 > 目标宽度：截取特定宽度，让其缩放后刚好为目标宽度。
                  if ( sw*scale > dw){
                      pw = dw/scale;
                  }

                  // 截取部分：[px,py,pw,ph]，其中dy是0
                  px = (sw-pw)/2;
                  this._enemyPreview.scale.x = scale;
                  this._enemyPreview.scale.y = scale;
                  this._enemyPreview.setFrame(px,py,pw,sh);
                  this._enemyPreview.opacity = 255;
                  // 如果缩放后宽度<目标宽度，或缩放后高度<小于目标高度，则按计算。
                if (sw*scale<dw)
                    this._enemyPreview.x = 58 + (dw-sw*scale)/2;
                else
                    this._enemyPreview.x = 58
                if(sh*scale<dh)
                    this._enemyPreview.y = 52 + (dh-sh*scale)/2;
                else
                    this._enemyPreview.y = 52

                 //特殊情况

                if([18,252,253,274,275,284].contains(this._enemy.id)){
                    this._enemyPreview.y = 52;
                }

                this._requestEnemyPreviewRefresh = false;
            }
        }
    }
};

setGlobal('Window_EnemyInfo', Window_EnemyInfo)